<template>
  <div>
    <Layout>
      <Sider hide-trigger :style="{ background: '#fff' }">
        <Menu active-name="/index/workbench" theme="light" width="auto" router>
          <MenuItem to="/index/workbench" name="/index/workbench"
            >工作台</MenuItem
          >
          <MenuItem to="/index/schedule" name="/index/schedule"
            >日期代办</MenuItem
          >
        </Menu>
      </Sider>
      <Layout :style="{ padding: '0 24px 24px' }">
        <Breadcrumb :style="{ margin: '24px 0' }">
          <BreadcrumbItem
            v-for="(item, index) in breadcrumbs"
            :key="index"
            @click="handleBreadcrumbClick(item)"
          >
            {{ item.title }}
          </BreadcrumbItem>
        </Breadcrumb>
        <Content
          :style="{ padding: '24px', minHeight: '280px', background: '#fff' }"
        >
          <router-view></router-view>
        </Content>
      </Layout>
    </Layout>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

interface BreadcrumbItem {
  title: string
  path?: string
}

const breadcrumbs = ref<BreadcrumbItem[]>([])

// 映射路径名称
const pathMap: Record<string, string> = {
  home: '首页',
  index: '控制台',
  workbench: '工作台',
  schedule: '日期代办'
}

const generateBreadcrumbs = () => {
  const matched = route.matched.filter((m) => m.name !== undefined && m.name !== null)
  const list: BreadcrumbItem[] = []

  for (let i = 0; i < matched.length; i++) {
    const routeRecord = matched[i]
    const name = String(routeRecord.name)
    const title = pathMap[name] || name

    list.push({
      title,
      path: routeRecord.path
    })
  }

  breadcrumbs.value = list
}

const handleBreadcrumbClick = (item: BreadcrumbItem) => {
  if (item.path) {
    router.push(item.path)
  }
}

onMounted(() => {
  generateBreadcrumbs()
})

watch(
  () => route.path,
  () => {
    generateBreadcrumbs()
  }
)
</script>

<style scoped>
</style>